<?php

namespace falcon5\inc\WPProviders;

use falcon5\inc\Base\ServiceProviderInterface;
use falcon5\inc\Http\Controllers\Rest\CallbackController;
use falcon5\inc\Http\Request;

/**
 * Class RestRoute
 * @package falcon5\inc\WPProviders
 * @desc REST API route configuration
 */
class RestRoute implements ServiceProviderInterface
{
    /**
     * REST API 命名空间
     */
    const API_NAMESPACE = 'falcon5/v1';

    /**
     * 控制器实例缓存
     */
    private $controllerInstances = [];

    /**
     * 获取控制器实例
     */
    private function getController(string $controllerClass)
    {
        if (!isset($this->controllerInstances[$controllerClass])) {
            if (!class_exists($controllerClass)) {
                throw new \Exception("Controller class {$controllerClass} not found");
            }
            $this->controllerInstances[$controllerClass] = new $controllerClass();
        }
        return $this->controllerInstances[$controllerClass];
    }

    /**
     * 路由配置
     */
    private $routes = [
        'callback' => [
            'controller' => CallbackController::class,
            'routes' => [
                'site_info' => [
                    'methods' => 'POST',
                    'callback' => 'siteInfoCallback',
                    'permission_callback' => '__return_true', // 公开访问
                    'args' => [
                        // 参数验证规则可以在这里添加
                    ],
                ],
                'entry_info' => [
                    'methods' => 'POST',
                    'callback' => 'entryInfoCallback',
                    'permission_callback' => '__return_true', // 公开访问
                    'args' => [
                        // 参数验证规则可以在这里添加
                    ],
                ],
                // 其他回调路由可以在这里添加
            ],
        ],
    ];

    /**
     * 注册 REST API 路由
     */
    public function register()
    {
        add_action('rest_api_init', [$this, 'registerRestRoutes']);
    }

    /**
     * 注册所有 REST 路由
     */
    public function registerRestRoutes()
    {
        foreach ($this->routes as $prefix => $group) {
            $this->registerRestGroup($prefix, $group);
        }
    }

    /**
     * 注册路由组
     */
    private function registerRestGroup(string $prefix, array $group)
    {
        $controllerClass = $group['controller'];
        $controller = $this->getController($controllerClass);

        foreach ($group['routes'] as $endpoint => $config) {
            $route = "/{$prefix}/{$endpoint}";

            register_rest_route(self::API_NAMESPACE, $route, [
                'methods' => $config['methods'],
                'callback' => function($wpRequest) use ($controller, $config) {
                    // 将 WP_REST_Request 转换为我们自己的 Request 对象
                    $customRequest = $this->convertRequest($wpRequest);
                    $customRequest->setAction($config['callback']);

                    // 调用控制器方法
                    $response = $controller->handleRequest($customRequest);
                    
                    // 将我们的 JsonResponse 转换为 WP_REST_Response
                    return $this->convertResponse($response);
                },
                'permission_callback' => $config['permission_callback'],
                'args' => $config['args'] ?? [],
            ]);
        }
    }

    /**
     * 将 WP_REST_Request 转换为自定义 Request
     */
    private function convertRequest(\WP_REST_Request $wpRequest)
    {
        $request = new Request();
        
        // 合并所有参数
        $params = array_merge(
            $wpRequest->get_url_params(),
            $wpRequest->get_query_params(),
            $wpRequest->get_body_params(),
            $wpRequest->get_json_params() ?: []
        );
        
        // 将参数添加到我们的请求对象
        foreach ($params as $key => $value) {
            $request->setParam($key, $value);
        }
        
        return $request;
    }

    /**
     * 将自定义 JsonResponse 转换为 WP_REST_Response
     */
    private function convertResponse(\falcon5\inc\Http\JsonResponse $response)
    {
        $data = [
            'code' => $response->getCode(),
            'msg' => $response->getMessage(),
            'data' => $response->getData(),
            'extra' => $response->getExtra(),
        ];
        
        $wpResponse = new \WP_REST_Response($data);
        
        // 设置适当的 HTTP 状态码
        $httpCode = 200;
        if ($response->getCode() !== 1) {
            $httpCode = 400; // 默认错误状态码
            
            // 可以根据自定义错误码映射到不同的 HTTP 状态码
            $errorCodeMap = [
                400 => 400, // Bad Request
                401 => 401, // Unauthorized
                403 => 403, // Forbidden
                404 => 404, // Not Found
                500 => 500, // Server Error
            ];
            
            if (isset($errorCodeMap[$response->getCode()])) {
                $httpCode = $errorCodeMap[$response->getCode()];
            }
        }
        
        $wpResponse->set_status($httpCode);
        
        return $wpResponse;
    }
} 